package com.amentretenimiento;

import java.io.File;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Login extends Activity implements Runnable{
	//	String urlamentretenimiento="http://201.155.80.190:8080/";
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

	//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";

	LoginSitesList loginsitesList = null;
	int var=0;
	String id_usuario;
	String usercom;
	String passcom;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	private ProgressDialog pd;
	LocationManager locationManager;
	SharedPreferences preferences ;
	public SharedPreferences.Editor editor;

	@Override
	protected void onResume() {
		super.onResume();
		//		gps();
	}

	private void startService() {
		Intent svc = new Intent(this, SystemService.class);
		startService(svc);
	}

	public void gps(){
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if(!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER) )
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("¿Desea activar el GPS?")
			.setCancelable(false)
			.setPositiveButton("Si", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
					startActivity(myIntent);  
					dialog.cancel();
					dialog.dismiss();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					gps();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
	}



	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);


		File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"AMEntretenimiento");
		directory.mkdirs();
		
		/****Reseteo preferencias
		 * 
		 * *****/
		SharedPreferences preferencias1 = getSharedPreferences("MisPreferencias", MODE_PRIVATE);
		SharedPreferences preferencias2 = getSharedPreferences("MenuSupervisor", MODE_PRIVATE);
		SharedPreferences preferencias3 = getSharedPreferences("MenuOperaciones", MODE_PRIVATE);
		SharedPreferences.Editor editor = preferencias1.edit();
		editor.clear();
		editor.commit();
		editor=preferencias2.edit();
		editor.clear();
		editor.commit();
		editor=preferencias3.edit();
		editor.clear();
		editor.commit();


		Button btn1 = (Button) findViewById(R.id.entrar);
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				EditText user=(EditText) findViewById(R.id.usuario);
				EditText pass=(EditText) findViewById(R.id.password);
				usercom = user.getText().toString();
				passcom = pass.getText().toString();

				if (usercom.equals("") && passcom.equals("")){
					AlertDialog alertdialog=new AlertDialog.Builder(Login.this).create();
					alertdialog.setIcon(R.drawable.icon);
					alertdialog.setTitle("Aviso");
					alertdialog.setMessage("Escribe usuario y password");
					alertdialog.show();
				}else{
					progreso();
				}
			}
		});
	}

	protected void progreso() {
		pd = ProgressDialog.show(this, "Espere por favor", "Buscando..", true, false);
		Thread thread = new Thread(this);
		thread.start();
	}

	public static boolean isInternetConnectionActive(Context context) {
		boolean bool = false;

		NetworkInfo networkInfo = ((ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();

		if(networkInfo == null || !networkInfo.isConnected()) {
			return false;
		}
		return true;
	}

	protected void LogIn(String usercom, String passcom) {
		try {

			spf = SAXParserFactory.newInstance();
			sp = spf.newSAXParser();
			xr = sp.getXMLReader();

			URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select*from+agente+where+idagente="+usercom+"+and+password='"+passcom+"'");
			Log.i("MII TAGG", ""+sourceUrl);
			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		loginsitesList = LoginMyXMLHandler.loginsitesList;

		int com = Integer.parseInt(""+loginsitesList.getrows().get(0));

		if(com == 1){
			String esSupervisor=loginsitesList.getEsSupervisor().get(0);
			Log.i("SOYSUPERVISOR", loginsitesList.getEsSupervisor().get(0));
			if(esSupervisor.equals("1")){
				Log.i("SERVICIO", "SERVICIO INICIADO");
				startService();
				preferences =  getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);


				//					editor.clear();



				editor = preferences.edit();

				Log.i("SOYSUPERVISOR", loginsitesList.getEsSupervisor().get(0));
				Intent ad1 = new Intent(Login.this, EsSupervisor.class);
				ad1.putExtra("idcia", ""+loginsitesList.getidCia().get(0).toString());

				editor.putString("idcia", ""+loginsitesList.getidCia().get(0).toString().trim());


				ad1.putExtra("idagente", ""+loginsitesList.getidAgente().get(0).toString());
				editor.putString("idagente", ""+loginsitesList.getidAgente().get(0).toString());

				//					para supervisor
				editor.putString("idagentesupervisor", ""+loginsitesList.getidAgente().get(0).toString());

				ad1.putExtra("nombre", ""+loginsitesList.getnombre().get(0).toString());

				editor.putString("nombreagente", ""+loginsitesList.getnombre().get(0).toString().trim());
				editor.commit();


				ad1.putExtra("NIP", ""+loginsitesList.getNIP().get(0).toString());
				ad1.putExtra("pass", ""+loginsitesList.getpassword().get(0).toString());
				ad1.putExtra("numcelular", ""+loginsitesList.getNumCelular().get(0).toString());
				ad1.putExtra("idCiaSupervisor", ""+loginsitesList.getIdCiaSupervisor().get(0).toString());
				ad1.putExtra("idAgenteSupervisor", ""+loginsitesList.getIdAgenteSupervisor().get(0).toString());
				ad1.putExtra("esSupervisor", ""+loginsitesList.getEsSupervisor().get(0).toString());
				startActivity(ad1);
				pd.dismiss();
				pd.cancel();
				//finish();
			}
			else{
				Log.i("SERVICIO", "SERVICIO INICIADO");
				startService();
				Intent ad = new Intent(Login.this, MenuResumen.class);
				ad.putExtra("idcia", ""+loginsitesList.getidCia().get(0).toString());
				ad.putExtra("idagente", ""+loginsitesList.getidAgente().get(0).toString());
				ad.putExtra("miusuario", ""+loginsitesList.getnombre().get(0).toString());
				preferences =  getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);;
				editor = preferences.edit();
				editor.putString("idagente", ""+loginsitesList.getidAgente().get(0).toString());

				editor.putString("nombreagente", ""+loginsitesList.getnombre().get(0).toString().trim());
				editor.putString("idcia", ""+loginsitesList.getidCia().get(0).toString().trim());
				editor.commit();

				ad.putExtra("NIP", ""+loginsitesList.getNIP().get(0).toString());
				ad.putExtra("pass", ""+loginsitesList.getpassword().get(0).toString());
				ad.putExtra("numcelular", ""+loginsitesList.getNumCelular().get(0).toString());
				ad.putExtra("idCiaSupervisor", ""+loginsitesList.getIdCiaSupervisor().get(0).toString());
				ad.putExtra("idAgenteSupervisor", ""+loginsitesList.getIdAgenteSupervisor().get(0).toString());
				ad.putExtra("esSupervisor", ""+loginsitesList.getEsSupervisor().get(0).toString());
				ad.putExtra("agente", ""+loginsitesList.getidAgente().get(0).toString());
				startActivity(ad);
				pd.dismiss();
				pd.cancel();
				//finish();
			}

		}
		else{

			var=1;
			handler.sendEmptyMessage(0);

		}
	}


	public void run() {

		try{
			if(isInternetConnectionActive(getApplicationContext())){
				LogIn(usercom, passcom);

			}else{
				var=2;
				pd.dismiss();
				pd.cancel();
				handler.sendEmptyMessage(0);
			}
		}catch (Exception e) {
			AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
			builder.setMessage("Error de conexión")
			.setCancelable(false)
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
	}
	//5002 ghg56
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {


			if (var == 1) {
				AlertDialog alertdialog=new AlertDialog.Builder(Login.this).create();
				alertdialog.setIcon(R.drawable.icon);
				alertdialog.setTitle("Aviso");
				alertdialog.setMessage("Usuario Incorrecto");
				alertdialog.show();
				pd.dismiss();
				pd.cancel();
			} else if(var == 2){  
				AlertDialog alertdialog=new AlertDialog.Builder(Login.this).create();
				alertdialog.setIcon(R.drawable.icon);
				alertdialog.setTitle("Aviso");
				alertdialog.setMessage("Error de conectividad");
				alertdialog.show();
				pd.dismiss();
				pd.cancel();

			}  
		}
	};

//	public void onBackPressed() {
//
//	};

}